<template>
  <div class="page">
    <van-empty v-if="list.finished && list.data.length < 1" :description="$t('common.noData')" />
    <van-list
      v-if="!list.finished || list.data.length > 0"
      v-model:loading="list.loading"
      :finished="list.finished"
      @load="getList"
      :immediate-check="false"
    >
      <div class="gift" v-for="item in list.data" :key="item.id" @click="detail(item)">
        <img :src="item.img" />
        <div class="title">
          <van-text-ellipsis :content="item.name" />
        </div>
        <div class="font-size-1.2rem">
          <span class="primary font-size-1.6rem">{{ item.points }} </span> {{ $t('home.home.credit') }}
        </div>
      </div>
    </van-list>
  </div>
</template>

<script setup lang="ts">
const { getList, list } = useList(apis.api.userGiftPage)

const { t } = useI18n()

const currGift = ref<ApiPointGift>()
const router = useRouter()

onMounted(async () => {
  list.loading = true
  getList()
})

const beforeClose = (action: string) => {
  return new Promise(resolve => {
    if (action == 'confirm') {
      apis.api
        .userGiftExchange({ id: currGift.value!.id })
        .then(() => {
          resolve(true)
          router.replace('/coupons')
        })
        .catch(() => resolve(false))
    } else {
      resolve(true)
    }
  })
}

const detail = (item: ApiPointGift) => {
  currGift.value = item
  showConfirmDialog({
    title: item.name,
    message: item.note,
    confirmButtonText: t('common.exchange'),
    cancelButtonText: t('common.cancel'),
    beforeClose: beforeClose
  })
}
</script>

<style lang="scss" scoped>
.page {
  box-sizing: border-box;
  min-height: 100vh;
  padding: 2rem 0 0 2rem;
  background-color: #fafafa;
}
.gift {
  box-sizing: border-box;
  display: inline-block;
  width: 15.7rem;
  margin: 0 2rem 2rem 0;
  background-color: #fff;
  padding: 10px;
  img {
    width: 13.7rem;
    height: 13.7rem;
  }
  .title {
    font-size: 1.6rem;
    font-weight: bold;
  }
}
</style>
